package cfca.payment.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;

public class SocketClient  {
	private String ip;
	private int port;
	
	public SocketClient(String ip, int port) {
		this.ip = ip;
		this.port = port;
	}

	public String send(String request) {
		Socket socket = null;
		OutputStream  os = null;
		InputStream is = null;
		int len = 0;
		byte[] reply = new byte[10240];
		try {
			socket = new Socket(ip, port);
			os = socket.getOutputStream();
			is = socket.getInputStream();
			os.write(request.getBytes("UTF-8"));
			len = is.read(reply);
			os.close();
			is.close();
			socket.close();
//			System.out.println(InetAddress.getLocalHost());

		} catch (Exception e) {
			e.printStackTrace();
		}
		finally{
			try {
				if(os != null)	os.close();
				if(is != null) 	is.close();
				socket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		try {
			return new String(reply, 0, len, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}
}
